//
//  MineView.m
//  dhfsAPP
//
//  Created by Devil on 2017/7/31.
//  Copyright © 2017年 Devil. All rights reserved.
//

#import "MineView.h"
#import "fsapp-Swift.h"
@interface MineView()

//导航视图
@property(strong,nonatomic)HeaderView *headerView;
//个人信息
@property(strong,nonatomic)UIView *messageView;
//列表
@property(strong,nonatomic)UITableView *tableView;
 //列表名
@property(strong,nonatomic)NSArray *cellName;
//头像
@property(strong,nonatomic)UIImageView *headerImgV;
//手机号
@property(strong,nonatomic)UILabel *phoneNumLabel,*userNameLable;

@end

@implementation MineView

#pragma mark - 懒加载
-(HeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT(128)) Title:@"个人中心"];
        
        _headerView.headerViewDelegate = self;
    }
    
    return _headerView;
}

-(UIView *)messageView{
    if (!_messageView) {
        _messageView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT(128), SCREEN_WIDTH, HEIGHT(158))];
        
        _messageView.backgroundColor = [UIColor whiteColor];
        
        [_messageView addSubview:self.headerImgV];
//        [_messageView addSubview:self.phoneNumLabel];
        NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"name"]);
        [_messageView addSubview:self.userNameLable];
    }
    
    return _messageView;
}

-(UIImageView *)headerImgV{
    if (!_headerImgV) {
//        _headerImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"头像"]];
        NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"img"]);
        _headerImgV = [[UIImageView alloc] init];
        if ([[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"img"]] isEqualToString:@""])
        {
            _headerImgV.image = [UIImage imageNamed:@"头像"];
        }
        else
        {
        [_headerImgV sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"img"]]];
        }
        
        _headerImgV.frame = CGRectMake(WIDTH(45), 0, WIDTH(96), HEIGHT(96));
        
        _headerImgV.center = CGPointMake(_headerImgV.center.x, HEIGHT(79));
        
        _headerImgV.layer.masksToBounds = YES;
        _headerImgV.layer.cornerRadius = WIDTH(48);
    }
    
    return _headerImgV;
}

-(UILabel *)phoneNumLabel{
    if (!_phoneNumLabel) {
        _phoneNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH(161), 0, 0, 0)];
        
        NSString *phoneNem = [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
        NSString *numberString = [phoneNem stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        
        _phoneNumLabel.text = numberString;
        _phoneNumLabel.textColor = RGB(51, 51, 51);
        _phoneNumLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:HEIGHT(26)];
        
        [_phoneNumLabel sizeToFit];
        
        _phoneNumLabel.center = CGPointMake(_phoneNumLabel.center.x, HEIGHT(69));
    }
    
    return _phoneNumLabel;
}

-(UILabel *)userNameLable{
    if (!_userNameLable)
    {
        _userNameLable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH(161), self.phoneNumLabel.frame.size.height + self.phoneNumLabel.frame.origin.y + HEIGHT(5), 0, 0)];
        
        _userNameLable.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
        _userNameLable.textColor = RGB(51, 51, 51);
        _userNameLable.font = [UIFont fontWithName:@"PingFangSC-Regular" size:HEIGHT(26)];
        
        [_userNameLable sizeToFit];
        
        _userNameLable.center = CGPointMake(_userNameLable.center.x, _messageView.frame.size.height / 2.0);
        
    }
    
    return _userNameLable;
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT(286), SCREEN_WIDTH, SCREEN_HEIGHT - HEIGHT(286))];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableView.backgroundColor = [UIColor whiteColor];
        
        _tableView.scrollEnabled = NO;
    }
    
    return _tableView;
}

-(NSArray *)cellName{
    if (!_cellName) {
        _cellName = [NSArray arrayWithObjects:@"我已购买",@"我的收藏",@"我的钱包",@"客服反馈",@"设置", nil];
    }
    
    return _cellName;
}
#pragma mark - 构造函数
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    
    if (self) {
        [self initUI];
    }
    
    return self;
}

#pragma mark - TableViewDelegate&TableViewDataSource实现
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0)
    {
        return 4;
    }
    else
    {
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT(100);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return HEIGHT(20);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT(20))];
    
    headerView.backgroundColor = RGB(241, 242, 242);
    
    return headerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = @"cell";
    UITableViewCell *cell = nil;
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    else
    {
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    cell.selectionStyle = NO;
    
    cell.backgroundColor = RGB(221,221, 221);
    
    UIView *cellView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT(99))];
    
    cellView.backgroundColor = [UIColor whiteColor];
    
    long num = 0;
    
    if (indexPath.section == 0)
    {
        num = indexPath.row;
    }
    else
    {
        num = indexPath.row + 4;
    }
    
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH(45), 0, WIDTH(42), HEIGHT(42))];
    
    imgV.image = [UIImage imageNamed:self.cellName[num]];
    imgV.center = CGPointMake(imgV.center.x, cellView.center.y);
    
    [cellView addSubview:imgV];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH(106), 0, 0, 0)];
    
    title.text = self.cellName[num];
    title.textColor = RGB(51, 51, 51);
    title.font = [UIFont fontWithName:@"PingFangSC-Regular" size:HEIGHT(26)];
    
    [title sizeToFit];
    title.center = CGPointMake(title.center.x, imgV.center.y);
    
    [cellView addSubview:title];
    
    [cell addSubview:cellView];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (indexPath.row == 2) {
            WalletViewController *vc = [[WalletViewController alloc] init];
            
            if ([self.mineViewDelegate respondsToSelector:@selector(pushVC:)]) {
                [self.mineViewDelegate pushVC:vc];
            }
        }
        if (indexPath.row == 0 && indexPath.section == 0) {
            boughtViewController *vc = [[boughtViewController alloc] init];
            
            if ([self.mineViewDelegate respondsToSelector:@selector(pushVC:)]) {
                [self.mineViewDelegate pushVC:vc];
            }
        }
        if (indexPath.row == 1 && indexPath.section == 0) {
            collectionViewController  *vc = [[collectionViewController alloc] init];
            
            if ([self.mineViewDelegate respondsToSelector:@selector(pushVC:)]) {
                [self.mineViewDelegate pushVC:vc];
            }
        }
        if (indexPath.row == 3 && indexPath.section == 0) {
            FeedbackViewController  *vc = [[FeedbackViewController alloc] init];
            
            if ([self.mineViewDelegate respondsToSelector:@selector(pushVC:)]) {
                [self.mineViewDelegate pushVC:vc];
            }
        }

        if (indexPath.section == 1) {
            SetViewController *vc = [[SetViewController alloc] init];
            
            if ([self.mineViewDelegate respondsToSelector:@selector(pushVC:)]) {
                [self.mineViewDelegate pushVC:vc];
            }
        }
    });
}

#pragma mark - MineViewDelegate实现
-(void)clickHeaderViewBtn{
    if ([self.mineViewDelegate respondsToSelector:@selector(backVC)]) {
        [self.mineViewDelegate backVC];
    }
}

#pragma mark - 连接服务器
-(void)login{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *parameters = @{
                                 @"udid":[[NSUserDefaults standardUserDefaults] objectForKey:@"idfa"]
                                 };
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/visitorLogin" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //                回调或者说是通知主线程刷新，
            int status = [responseObject[@"status"] intValue];
            
            if(status == 200){
                NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                
                NSDictionary *resposeDic = response.allHeaderFields;
                
                NSString *str = resposeDic[@"Set-Cookie"];
                str = [str stringByReplacingOccurrencesOfString:@"; path=/" withString:@""];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                [user setObject:str forKey:@"Cookie"];
                [user setObject:responseObject[@"result"][@"name"] forKey:@"name"];
                [user setObject:responseObject[@"result"][@"img"] forKey:@"img"];
                
                [self isLogin];
               
            }else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"发生未知错误，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil]];
                
                if ([self.mineViewDelegate respondsToSelector:@selector(login:)])
                {
                    [self.mineViewDelegate login:alert];
                }
            }
        });
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

#pragma mark - 其他函数
-(void)initUI{
    [self addSubview:self.headerView];
    
    [self addSubview:self.messageView];
    
    [self addSubview:self.tableView];
}

//未登录
-(void)isNotLogin{
    self.phoneNumLabel.text = @"未登录";
    [self.phoneNumLabel sizeToFit];
    _phoneNumLabel.center = CGPointMake(_phoneNumLabel.center.x, HEIGHT(69));
    
    self.userNameLable.text = @"未登录";
    [self.userNameLable sizeToFit];
    _userNameLable.center = CGPointMake(_userNameLable.center.x, HEIGHT(69));

    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
    
    self.messageView.userInteractionEnabled = YES;
    
    [self.messageView addGestureRecognizer:tap];
    
    self.headerImgV.image = [UIImage imageNamed:@"头像"];
    
    _headerImgV.frame = CGRectMake(WIDTH(45), 0, WIDTH(96), HEIGHT(96));
    
    _headerImgV.center = CGPointMake(_headerImgV.center.x, HEIGHT(79));
    
    _headerImgV.layer.masksToBounds = YES;
    _headerImgV.layer.cornerRadius = WIDTH(48);

}

-(void)isLogin{
//    NSString *phoneNem = [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
//    NSString *numberString = [phoneNem stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
//    
//    self.phoneNumLabel.text = numberString;
//    [self.phoneNumLabel sizeToFit];
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"name"]);
    self.userNameLable.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    
    [self.userNameLable sizeToFit];
    
    self.messageView.userInteractionEnabled = NO;
    
    [_headerImgV sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"img"]]];
}

-(void)click{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择登录方式" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *accountAction = [UIAlertAction actionWithTitle:@"以普通用户登录（推荐）" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([self.mineViewDelegate respondsToSelector:@selector(login:)])
        {
            LoginViewController *vc = [[LoginViewController alloc] init];
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
            
            [self.mineViewDelegate login:nav];
        }
    }];
    
    UIAlertAction *touristAction = [UIAlertAction actionWithTitle:@"以游客身份登录（仅可在本机充值）" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoadViewController *load = [[LoadViewController alloc] init];
        [load Alarequest];
        dispatch_async(dispatch_get_main_queue(), ^{
//            if ([self.mineViewDelegate respondsToSelector:@selector(reloadUI)])
//            {
//                [self.mineViewDelegate reloadUI];
//            }
            [self login];
        });
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:accountAction];
    [alert addAction:touristAction];
    [alert addAction:cancelAction];
    
    if ([self.mineViewDelegate respondsToSelector:@selector(login:)])
    {
        [self.mineViewDelegate login:alert];
    }
}
@end
